<?php

namespace app\admin\controller\pigai;

use app\common\controller\Backend;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\Loader;
use think\response\Json;

/**
 * 服务单录入查询需要的字段集合
 *
 * @icon fa fa-circle-o
 */
class Shenhess extends Backend
{

    /**
     * Shenhes模型对象
     * @var \app\admin\model\lists\Shenhes
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\pigai\Shenhe;
        $this->view->assign("statusList", $this->model->getStatusList());
        $jigoudata = ['' => '请选择业务来源', '直属业务' => '直属业务', '直接业务' => '直接业务', '分支机构' => '分支机构', '合作商' => '合作商', '查勘机构' => '查勘机构', '招商业务' => '招商业务', '合作业务 ' => '合作业务'];
        $this->view->assign('jigoudata', $jigoudata);
        $chexing = Config::get('site.chexing');
        $this->view->assign('chexing', $chexing);
        $xingzhi = Config::get('site.xingzhi');
        $this->view->assign('xingzhi', $xingzhi);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $where1['status'] = 3;
        $list             = $this->model
            ->where($where)
            ->where($where1)
            ->order($sort, $order)
            ->paginate($limit);
        $result           = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 浏览
     * @param $ids
     * @return void
     * @throws DbException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function details($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $admin    = $this->auth->getUserInfo();
        $adminIds = $this->getDataLimitAdminIds();

        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $row['car_register']   = date('Y-m-d', $row['car_register']);
        $row['plan_strattime'] = date('Y-m-d H:i:s', $row['plan_strattime']);
        $row['plan_endtime']   = date('Y-m-d H:i:s', $row['plan_endtime']);
        $this->view->assign('row', $row);


        // 处理组织信息并赋值给模板
        $select = selectMenus_zuzhi($admin['zuzhi']);
        $this->assign('selectMenu', $select);

        $ying = Db::name('tong_files')->where('tong_id', $row['ids'])->select();
        $this->assign('file', $ying);


        $yijian = Db::name('yijian')->where('did', $row['ids'])->select();
        $this->assign('yijian', $yijian);

        $this->assign('admin', $admin);
        return $this->view->fetch();
    }

    //退回上一步
    public function tuihuishiji()
    {
        $id                = $_POST['id'];
        $data['shen_time'] = time();
        $data['shen_peo']  = $_POST['shenhe_peo'];

        $admin           = $this->auth->getUserInfo();
        $data['user_id'] = $admin['id'];

        $three = Db::name('list_three')->where('id', $id)->where(['status' => 3])->field('id,batch_state,ids')->find();
        if (!$three) {
            return json(['code' => -1, 'msg' => '系统错误']);
        }
        $data['did'] = $three['ids'];
        $batch_state = $three['batch_state']; //1-退单 2-改单（初审） 3-增单（初审、财务）
        // 启动事务
        Db::startTrans();
        try {
            if ($_POST['shenhe_yijian'] == '') {
                return json(['code' => -1, 'msg' => '请填写审核意见']);
            } else {
                $data['shen_yijian'] = $_POST['shenhe_yijian'];
                $res                 = Db::name('yijian')->insert($data);
                $dataa['status']     = 6; // 市级审核
                if ($batch_state == '2') {
                    //退回初级审核
                    $dataa['status'] = 2;
                }
                $ress = Db::name('list_three')->where('id', $id)->update($dataa);

            }
            // 提交事务
            Db::commit();
            return json(['code' => 1, 'msg' => '请求成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 0, 'msg' => '失败' . $e->getMessage() . '，异常行：' . $e->getLine() . '，异常路径：' . $e->getfile()]);
        }

    }

    //退回修改
    public function tuihui()
    {
        $id                = $_POST['id'];
        $data['shen_time'] = time();
        $data['shen_peo']  = $_POST['shenhe_peo'];

        $admin           = $this->auth->getUserInfo();
        $data['user_id'] = $admin['id'];
        $three           = Db::name('list_three')->where('id', $id)->where(['status' => 3])->field('id,ids')->find();
        if (!$three) {
            return json(['code' => -1, 'msg' => '系统错误']);
        }
        $data['did'] = $three['ids'];
        // 启动事务
        Db::startTrans();
        try {
            if ($_POST['shenhe_yijian'] == '') {
                return json(['code' => -1, 'msg' => '请填写审核意见']);
            } else {
                $data['shen_yijian'] = $_POST['shenhe_yijian'];
                $res                 = Db::name('yijian')->insert($data);
                $dataa['status']     = 4;
                $ress                = Db::name('list_three')->where('id', $id)->update($dataa);
            }
            // 提交事务
            Db::commit();
            return json(['code' => 1, 'msg' => '请求成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 0, 'msg' => '失败' . $e->getMessage() . '，异常行：' . $e->getLine() . '，异常路径：' . $e->getfile()]);
        }

    }

    //通过审核
    public function pzuihou()
    {
        $id = $_POST['id'];


        $data['shen_time'] = strtotime($_POST['shenhe_time']);
        $data['shen_peo']  = $_POST['shenhe_peo'];

        $dataa['status']         = 5;
        $dataa['yw_shenhe_time'] = time();
        $dataa['yw_finance_peo'] = $_POST['shenhe_peo'];
        $admin                   = $this->auth->getUserInfo();
        $data['user_id']         = $admin['id'];
        $three                   = Db::name('list_three')->where('id', $id)->where(['status' => 3])->field('id,batch_state,ids')->find();
        if (!$three) {
            return json(['code' => -1, 'msg' => '系统错误']);
        }
        $data['did'] = $three['ids'];

        // 启动事务
        Db::startTrans();
        try {
            if ($_POST['shenhe_yijian'] == '') {
                $data['shen_yijian'] = '财务审核(批单)通过';
            } else {
                $data['shen_yijian'] = $_POST['shenhe_yijian'];
            }
            $res = Db::name('yijian')->insert($data);


            $res     = Db::name('list_three')->where('id', $id)->update($dataa);
            genghuan_one($id);
            // 提交事务
            Db::commit();
            return json(['code' => 1, 'msg' => '请求成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 0, 'msg' => '失败' . $e->getMessage() . '，异常行：' . $e->getLine() . '，异常路径：' . $e->getfile()]);
        }


    }
}
